<template>
    <div>
        <Card>
            <!--搜索框-->
            <Form :model="search" ref="form1" label-position="right" :label-width="90" inline>
                <FormItem label="MAC" prop="dtuMac">
                    <div class="filters-input">
                        <Input type="text" v-model="search.dtuMac" placeholder="请输入MAC" class="normal-input"/>
                    </div>
                </FormItem>
                <FormItem label="小区名称">
                    <div class="filters-input">
                        <el-select v-model="search.housingId" placeholder="请选择小区" filterable
                                   clearable no-data-text="暂无数据">
                            <el-option v-for="item in houseList" :value="item.id" :key="item.id"
                                       :label="item.name"></el-option>
                        </el-select>
                    </div>
                </FormItem>
                <FormItem>
                    <Button type="primary" icon="ios-search" @click="handleQuery('form1')">搜索</Button>
                </FormItem>
            </Form>

            <Row class="form-row">
                <!--<Button type="primary" icon="md-add" @click="modalEdit = true;modalType = 'add';guardInfo = {}">新增-->
                <Button type="primary" icon="md-add" @click="handleAdd()">新增
                </Button>
            </Row>
            <!--内容 表单-->

            <el-table stripe border :loading="tableLoading" :data="tableData" style="width: 100%">
                <template slot="empty">暂无数据</template>
                <el-table-column prop="houseName" label="小区名"></el-table-column>
                <el-table-column prop="brandName" label="品牌"></el-table-column>
                <el-table-column prop="dtuMac" label="MAC"></el-table-column>
                <el-table-column prop="deviceGroup" label="组团"></el-table-column>
                <el-table-column prop="deviceBuild" label="楼栋"></el-table-column>
                <el-table-column prop="deviceUnit" label="单元"></el-table-column>
                <el-table-column prop="location" label="安装位置"></el-table-column>
                <el-table-column label="设备类型">
                    <template slot-scope="scope">
                        <p v-if="scope.row.type==1" style="color: blue">围墙机</p>
                        <p v-if="scope.row.type==2" style="color: green">单元机</p>
                    </template>
                </el-table-column>
                <el-table-column prop="onlineTime" label="最后在线时间"></el-table-column>
                <el-table-column prop="isOnline" label="门禁状态" width="150" align="center">
                    <template slot-scope="scope">
                        <p v-if="scope.row.isOnline == 1" style="color:green">在线</p>
                        <p v-if="scope.row.isOnline == 0" style="color:red">离线</p>
                    </template>
                </el-table-column>
                <el-table-column label="按钮组" width="150" align="center">
                    <template slot-scope="scope">
                        <el-dropdown>
                            <el-button type="primary">
                                操作<i class="el-icon-arrow-down el-icon--right"></i>
                            </el-button>
                            <el-dropdown-menu slot="dropdown" align="center">
                                <el-dropdown-item @click.native="HandleEdit(scope.row.id)">修改</el-dropdown-item>
                                <!--<el-dropdown-item @click.native="HandleRestart(scope.row)">强制重启</el-dropdown-item>-->
                                <el-dropdown-item @click.native="handleLog(scope.row)">查看日志</el-dropdown-item>
                                <el-dropdown-item @click.native="HandleCode(scope.row)">查看二维码</el-dropdown-item>
                                <el-dropdown-item @click.native="HandleDelete(scope.row.id)">删除</el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                    </template>
                </el-table-column>
            </el-table>

            <Page style="margin: 10px 0;" :total="pageTotal" :current="pageNum" :page-size="pageSize" show-total
                  show-sizer show-elevator @on-change="handlePage" @on-page-size-change='handlePageSize'>
            </Page>

        </Card>

        <Modal v-model="modalEdit" :title="modalType == 'add' ? '新增': '修改'">
            <Form ref="saveGuardInfo" :model="guardInfo" :rules="guardRules" :label-width="90">
                <FormItem label="设备类型" prop="type">
                    <el-select v-model="guardInfo.type">
                        <el-option
                            v-for="item in deviceTypeOptions"
                            :key="item.value"
                            :value="item.value"
                            :label="item.label">
                        </el-option>
                    </el-select>
                </FormItem>
                <FormItem label="品牌名称" prop="brandId">
                    <el-select v-model="guardInfo.brandId" placeholder="请选择品牌" filterable

                               style="width:100%" no-data-text="暂无数据">
                        <el-option v-for="item in brandList" :value="item.id" :key="item.id"
                                   :label="item.name"></el-option>
                    </el-select>
                </FormItem>
                <FormItem label="MAC" prop="dtuMac">
                    <Input v-model="guardInfo.dtuMac" placeholder="MAC" class="normal-input"></Input>
                </FormItem>
                <FormItem label="小区名称" prop="housingId">
                    <el-select v-model="guardInfo.housingId" @change="housechange" placeholder="请选择小区" filterable style="width:100%" no-data-text="暂无数据">
                        <el-option v-for="item in houseList" :value="item.id" :key="item.id"
                                   :label="item.name"></el-option>
                    </el-select>
                </FormItem>
                <div v-show="this.guardInfo.type==2">
                    <FormItem label="组团">
                        <el-select v-model="guardInfo.deviceGroup" @change="groupchange" placeholder="请选择组团" filterable no-data-text="暂无数据">
                            <el-option v-for="item in groupList" :key="item.label" :label="item.label" :value="item.label">
                            </el-option>
                        </el-select>
                    </FormItem>
                    <FormItem label="楼栋">
                        <el-select v-model="guardInfo.deviceBuild" @change="buildingchange" placeholder="请选择楼栋" filterable no-data-text="暂无数据">
                            <el-option v-for="item in buildList" :value="item.label" :key="item.label" :label="item.label"></el-option>
                        </el-select>
                    </FormItem>
                    <FormItem label="单元">
                        <el-select v-model="guardInfo.deviceUnit" placeholder="请选择单元" filterable no-data-text="暂无数据">
                            <el-option v-for="item in unitList" :key="item.label" :value="item.label"  :label="item.label">
                            </el-option>
                        </el-select>
                    </FormItem>
                </div>
                <FormItem label="位置" prop="location">
                    <Input v-model="guardInfo.location" placeholder="请输入位置" class="normal-input"></Input>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button type="text" size="large" @click="onCancel()">关闭</Button>
                <Button type="primary" size="large" @click="handleSubmit" :loading="saveGuardInfoLoading">确定</Button>
            </div>
        </Modal>

        <Modal v-model="modalCode" title="生成二维码">
            <div class="codeBody">
                <img :src="codeImg" alt="">
            </div>
            <div slot="footer">
                <Button type="primary" size="large" @click="onCancel()">确定</Button>
            </div>
        </Modal>

        <el-dialog title="DTU日志" :visible.sync="dialogLogVisible" :append-to-body="true">
            <el-card id="log-card" style="height: 400px; overflow-y: scroll; ">
                <el-alert v-for="item, index in logList" :key="'log-' + index" style="margin-bottom: 10px"
                          :title="item.content"
                          :description="item.timestamp"
                          :type="item.type == 'in' ? 'info' : 'success'" :closable="false">
                </el-alert>
            </el-card>
            <span slot="footer" class="dialog-footer">
                <el-form :inline="true" >
                    <el-form-item>
                        <el-input v-model="message" placeholder="请输入内容"></el-input>
                    </el-form-item>
                    <el-form-item>
                    <el-button type="primary" @click.native="handleSend">发送</el-button>
                    </el-form-item>
                </el-form>
            </span>
        </el-dialog>

    </div>
</template>


<script>
    import {getDate} from "../../libs/tools"
    let loadData = function () {
        if (this.tableLoading) return;
        this.tableLoading = true;
        let params = this.search;
        params.pageNum = this.pageNum;
        params.pageSize = this.pageSize;
        //与后台交换数据
        this.postRequest("/api/doorDtu/loadData", params).then(res => {
            this.tableLoading = false;
            if (res.code == 20000) {
                this.tableData = res.data.list;
                this.pageTotal = res.data.total;
            } else {
                this.tableData = [];
                this.$Message.error({
                    content: res.message,
                    duration: 5
                });
            }
        });
    };
    export default {
        data() {
            return {
                search: {},
                pageSize: "",
                pageNum: 1,
                //每页数量
                pageSize: 10,
                //总数
                pageTotal: 0,
                //数据表格隐藏那个状态
                tableLoading: false,
                tableData: [],
                groupList:[],
                buildList:[],
                unitList:[],
                logList: [],
                dialogLogVisible: false,
                message: null,
                guardRules: {
                    housingId: [
                        {required: true, message: "请选择小区名称"}
                    ],
                    brandId: [
                        {required: true, message: "请选择品牌名称"}
                    ],
                    dtuMac: [
                        {required: true, message: "请输入MAC", trigger: "blur"}
                    ],
                    location: [
                        {required: true, message: "请输入地址", trigger: "blur"}
                    ],
                    type:[
                        {required: true, message: "请选择设备类型"}
                    ]
                },
                //小区列表
                houseList: [],
                //品牌列表
                brandList: [],
                deviceTypeOptions:[
                    {
                        value:1,
                        label:"围墙机",
                    },
                    {
                        value:2,
                        label:"单元机",
                    }
                ],
                modalType: 'add',
                modalEdit: false,
                guardInfo: {},
                saveGuardInfoLoading: false,
                // 二维码
                modalCode: false,
                codeImg: '',
                timer: null,
                currentRow: null
            };
        },

        created: function () {
            //加载数据
            this.loadData();
            this.gethouse();
        },
        mounted: function () {
            if (this.timer) {
                clearInterval(this.timer)
            } else {
                this.timer = setInterval(() => {
                    if (this.currentRow && this.dialogLogVisible == true)
                    this.dumpLog()
                }, 5000)
            }
        },
        updated: function () {
            this.$nextTick(() => {
                if (this.dialogLogVisible == true) {
                    let card =  document.getElementById('log-card')
                    card.scrollTop = card.scrollHeight
                }
            })
        },
        destroyed: function () {
          if (this.timer)  {
              clearInterval(this.timer)
          }
        },
        methods: {
            loadData,
            //加载小区
            gethouse: function () {
                this.postRequest("/api/housing/getHousingByLogin").then(res => {
                    this.houseList = res;
                });
            },
            housechange(value){
                this.groupList=[];
                this.buildList=[];
                this.unitList=[];
                this.getRequest("/api/room/queryGroupName?housingId=" + value).then(res => {
                    if (res.data.groupList != null) {
                        this.groupList = res.data.groupList;
                    } else if (res.data.buildList != null) {
                        this.buildList = res.data.buildList;
                    } else if (res.data.unitList != null) {
                        this.unitList = res.data.unitList;
                    }
                    this.loadData();
                });
            },
            groupchange(value){
                let housingId=this.guardInfo.housingId==null?this.filters.housingId:this.guardInfo.housingId;
                this.getRequest("/api/room/queryBuilding?groupName="+value+"&housingId="+housingId).then(resp => {
                    if (resp.data.buildList != null) {
                        this.buildList = resp.data.buildList;
                    } else if (resp.data.unitList != null) {
                        this.unitList = resp.data.unitList;
                    }
                });
            },
            buildingchange(){
                let housingId=this.guardInfo.housingId==null?this.filters.housingId:this.guardInfo.housingId;
                let params={};
                params.housingId = housingId;
                params.groupName = this.guardInfo.groupName;
                this.postRequest("/api/room/queryUnit",params).then(res => {
                    if (res.data.unitList != null) {
                        this.unitList = res.data.unitList;
                    } else {
                        this.roomList = res.data.roomList;
                    }
                });
            },
            handlePage(value) {
                this.pageNum = value;
                this.loadData();
            },
            handlePageSize(value) {
                this.pageSize = value;
                this.loadData();
            },
            //查询
            handleQuery(name) {
                this.search.pageNum = 1;
                this.$refs[name].validate(valid => {
                    if (valid) {
                        this.loadData();
                    }
                });
            },
            //删除按钮
            HandleDelete(id) {
                this.getRequest("/api/doorDtu/deleteById?id=" + id).then(res => {
                    this.tableLoading = false;
                    if (res.code == 20000) {
                        this.$Message.success("删除成功!");
                        this.pageNum = 1;
                        this.loadData();
                    } else {
                        this.$Message.error({
                            content: res.message,
                            duration: 50
                        });
                    }
                });
            },
            onCancel: function () {
                this.modalEdit = false;
                this.modalCode = false;
            },
            //确认按钮
            handleSubmit: function () {
                this.$refs['saveGuardInfo'].validate(valid => {
                    if (valid) {
                        this.postRequest("/api/doorDtu/saveOrUpdate", this.guardInfo).then(res => {
                            this.saveGuardInfoLoading = false;
                            if (res.code == 20000) {
                                this.$Message.success("操作成功！")
                                this.modalEdit = false
                                this.loadData()
                                return
                            }
                            this.$Message.error(res.message)

                        })
                    }
                })
            },
            //    编辑按钮
            HandleEdit: function (id) {
                this.modalEdit = true
                this.modalType = 'edit'
                this.getRequest("/api/doorDtu/openModel?id=" + id).then(res => {
                    this.houseList = res.data.houseList;
                    this.brandList = res.data.brandList;
                    this.guardInfo = res.data.doorDutCustom;
                    console.info(this.guardInfo);
                });
            },
            //新增按钮
            handleAdd: function () {
                this.modalEdit = true
                this.modalType = 'add'
                this.getRequest("/api/doorDtu/openModel").then(res => {
                    this.houseList = res.data.houseList;
                    this.brandList = res.data.brandList;
                    this.guardInfo = {};
                });
            },
            // 重启按钮
            HandleRestart: function (row) {
                this.$Message.success("功能暂未开发！")
            },
            //生成二维码
            HandleCode: function (row) {
                this.getRequest("api/doorDtu/qrcode?id=" + row.id).then(res => {
                    console.log(res);
                    if (res.code == 20000) {
                        this.codeImg = res.data;
                        this.modalCode = true;
                        return
                    }
                    this.$Message.error(res.message)
                });
                // this.$Message.success("功能暂未开发！")
            },
            handleLog: function (row) {
                this.currentRow = row
                this.dumpLog()
            },
            dumpLog: function () {
                const row = this.currentRow
                this.getRequest("api/doorDtu/dump/" + row.dtuMac).then(res => {
                    console.log(res);
                    if (res.code == 20000) {
                        if (res.data) {
                            for (const item of res.data) {
                                item.timestamp = getDate(item.timestamp, 'year')
                            }
                        }
                        this.logList= res.data;
                        this.dialogLogVisible = true;

                        return
                    }
                    this.$Message.error(res.message)
                });
            },
            handleSend: function () {
                if (!this.message) {
                    return
                }
                const params = {mac: this.currentRow.dtuMac, msg: this.message}
                this.postRequest("api/doorDtu/push", params).then(res => {
                    if (res.code == 20000) {
                        if (res.data === true) {
                            this.dumpLog()
                            return
                        }
                        this.$Message.error("发送失败，请稍后重试")
                        return
                    }
                    this.$Message.error(res.message)
                })
            }
        }
    };
</script>

<style lang="less">
    .codeBody {
        text-align: center;
    }
</style>
